package com.insist.controller;

import com.insist.entity.UserInfo;
import com.insist.framework.CmmBaseResponse;
import com.insist.model.AccountFlowModel;
import com.insist.service.UserService;
import com.insist.util.CmmUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 用户基础行为控制器
 * Created by INSIST on 2016/6/25.
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/userInfo")
    @ResponseBody
    public UserInfo userInfo(HttpServletRequest request, Model model) {
        Subject currentUser = SecurityUtils.getSubject();
        Long id = (Long)currentUser.getPrincipal();
        if(id == null){
            return new UserInfo();
        }
        UserInfo user = userService.getById(id);
        user.setPassword(null);
        if(StringUtils.isEmpty(user.getUsername())){
            user.setUsername(user.getMobile());
        }
        return user;
    }

    @RequestMapping(value = "/findAccountFlow")
    @ResponseBody
    public List<AccountFlowModel> findAccountFlow(){
        return userService.findAccountFlow(CmmUtils.getLoginUserId());
    }


    @RequestMapping(value = "/logout")
    @ResponseBody
    public CmmBaseResponse logout() {
        try {
            Subject currentUser = SecurityUtils.getSubject();
            currentUser.logout();
            return CmmBaseResponse.buildResponse(true, "登出成功");
        }catch (Exception e){
            return CmmBaseResponse.buildResponse(false, "登出失败");
        }
    }

    /**
     * 实际的登录代码
     * 如果登录成功，跳转至首页；登录失败，则将失败信息反馈对用户
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/dologin")
    @ResponseBody
    public CmmBaseResponse doLogin(HttpServletRequest request, Model model) {
        CmmBaseResponse responce = new CmmBaseResponse();
        responce.setSuccess(true);
        responce.setMessage("登录成功");
        String msg = "";
        String userName = request.getParameter("username");
        String password = request.getParameter("password");

        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        token.setRememberMe(true);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            if (subject.isAuthenticated()) {
                UserInfo userInfo = CmmUtils.getLoginUser();
                userInfo.setPassword("");
                responce.setData(userInfo);
                return responce;
            } else {
                UserInfo userInfo = CmmUtils.getLoginUser();
                userInfo.setPassword("");
                responce.setData(userInfo);
                return responce;
            }
        } catch (IncorrectCredentialsException e) {
            msg = "登录密码错误." ;
            model.addAttribute("message", msg);
            return CmmBaseResponse.buildResponse(false,msg);
        } catch (ExcessiveAttemptsException e) {
            msg = "登录失败次数过多";
            model.addAttribute("message", msg);
            return CmmBaseResponse.buildResponse(false,msg);
        } catch (LockedAccountException e) {
            msg = "帐号已被锁定. The account for username " + token.getPrincipal() + " was locked.";
            model.addAttribute("message", msg);
            return CmmBaseResponse.buildResponse(false,msg);
        } catch (DisabledAccountException e) {
            msg = "帐号已被禁用. The account for username " + token.getPrincipal() + " was disabled.";
            model.addAttribute("message", msg);
            return CmmBaseResponse.buildResponse(false,msg);
        } catch (ExpiredCredentialsException e) {
            msg = "帐号已过期. " ;
            model.addAttribute("message", msg);
            return CmmBaseResponse.buildResponse(false,msg);
        } catch (UnknownAccountException e) {
            msg = "帐号或密码错误. ";
            model.addAttribute("message", msg);
            return CmmBaseResponse.buildResponse(false,msg);
        } catch (UnauthorizedException e) {
            msg = "" + e.getMessage();
            model.addAttribute("message", msg);
            return CmmBaseResponse.buildResponse(false,msg);
        }
    }


    @RequestMapping(value = "/editInfo")
    @ResponseBody
    public CmmBaseResponse editInfo(@RequestParam(required = false)String username,
                                    @RequestParam(required = false)String realname,
                                    @RequestParam(required = false)String address,
                                    @RequestParam(required = false)String image,
                                    @RequestParam(required = false)String mobile) {
        try {
            UserInfo userInfo = CmmUtils.getLoginUser();
            if(!StringUtils.isEmpty(username)){
                userInfo.setUsername(username);
            }
            if(!StringUtils.isEmpty(realname)){
                userInfo.setRealname(realname);
            }
            if(!StringUtils.isEmpty(address)){
                userInfo.setAddress(address);
            }
            if(!StringUtils.isEmpty(image)){
                userInfo.setImage(image);
            }
            if(!StringUtils.isEmpty(mobile)){
                userInfo.setRecMobile(mobile);
            }
            CmmBaseResponse response = CmmBaseResponse.buildResponse(true, "修改成功");
            userService.save(userInfo);
            userInfo.setPassword("");
            response.setData(userInfo);
            return response;
        }catch (Exception e){
            e.printStackTrace();
            return CmmBaseResponse.buildResponse(false, "修改失败");
        }
    }



    @RequestMapping("/trideCoin")
    @ResponseBody
    public CmmBaseResponse trideCoin(Double coin,String mobile){
        return userService.trideCoin(coin,mobile,CmmUtils.getLoginUserId());
    }

}
